package cn.congzhou.crm.service.impl;


import cn.congzhou.crm.domain.Permission;
import cn.congzhou.crm.mapper.PermissionMapper;
import cn.congzhou.crm.query.QueryObject;
import cn.congzhou.crm.service.IPermissionService;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import org.apache.shiro.authz.annotation.RequiresPermissions;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.ApplicationContext;
import org.springframework.stereotype.Controller;
import org.springframework.stereotype.Service;

import java.lang.reflect.Method;
import java.util.Collection;
import java.util.List;

@Service
public class PermissionServiceImpl implements IPermissionService {

    @Autowired
    private PermissionMapper permissionMapper;

    @Autowired
    private ApplicationContext ctx;

    @Override
    public int deleteByPrimaryKey(Long id) {
        if (id != null) {
            permissionMapper.deleteByPrimaryKey(id);
        }
        return 0;
    }


    @Override
    public Permission selectByPrimaryKey(Long id) {
        Permission per = permissionMapper.selectByPrimaryKey(id);
        return per;
    }

    @Override
    public List<Permission> selectAll() {
        List<Permission> per = permissionMapper.selectAll();
        return per;
    }

    @Override
    public void saveOrUpdate(Permission per) {
        if (per.getId() != null) {
            permissionMapper.updateByPrimaryKey(per);
        } else {
            permissionMapper.insert(per);
        }
    }

    @Override
    public PageInfo<Permission> selectByPage(QueryObject qo) {
//      在调用查询方法前执行分页方法，此方法有效一次有效
        PageHelper.startPage(qo.getCurrentPage(),qo.getPageSize());
        List<Permission> list = permissionMapper.selectByPage(qo);
//      创建结果集对象返回
        PageInfo<Permission> pageInfo = new PageInfo<>(list);

        return pageInfo;
    }


    /**
     * 加载系统权限
     */
    @Override
    public void reload() {
//      获取贴有Controller注解的bean对象
        Collection<Object> beans = ctx.getBeansWithAnnotation(Controller.class).values();
//      查询所有权限表达式
        List<String> expressions = permissionMapper.selectAllExpression();
//      遍历所有对象，获取bean对象中的方法
        for (Object bean : beans) {
            Method[] methods = bean.getClass().getSuperclass().getDeclaredMethods();

            for (Method method : methods) {
//              遍历所有方法，获取方法上面的RequirePermission注解
                RequiresPermissions anno = method.getAnnotation(RequiresPermissions.class);
                if (anno != null&& !expressions.contains(anno.value()[1])) {
                    permissionMapper.insert(new Permission(null, anno.value()[0], anno.value()[1],null));

                }
            }
        }
    }

}
